<?php

namespace App\Utils;

use Request;
use App\Utils\Blogger;

class Utils {

    /**
     * @return mixed
     */
    public static function route_class() {
        return str_replace('.', '-', Route::currentRouteName());
    }

    public static function SBC_DBC($str, $args2) {
        $DBC = Array(
            '０', '１', '２', '３', '４',
            '５', '６', '７', '８', '９',
            'Ａ', 'Ｂ', 'Ｃ', 'Ｄ', 'Ｅ',
            'Ｆ', 'Ｇ', 'Ｈ', 'Ｉ', 'Ｊ',
            'Ｋ', 'Ｌ', 'Ｍ', 'Ｎ', 'Ｏ',
            'Ｐ', 'Ｑ', 'Ｒ', 'Ｓ', 'Ｔ',
            'Ｕ', 'Ｖ', 'Ｗ', 'Ｘ', 'Ｙ',
            'Ｚ', 'ａ', 'ｂ', 'ｃ', 'ｄ',
            'ｅ', 'ｆ', 'ｇ', 'ｈ', 'ｉ',
            'ｊ', 'ｋ', 'ｌ', 'ｍ', 'ｎ',
            'ｏ', 'ｐ', 'ｑ', 'ｒ', 'ｓ',
            'ｔ', 'ｕ', 'ｖ', 'ｗ', 'ｘ',
            'ｙ', 'ｚ', '－', '　', '：',
            '．', '，', '／', '％', '＃',
            '！', '＠', '＆', '（', '）',
            '＜', '＞', '＂', '＇', '？',
            '［', '］', '｛', '｝', '＼',
            '｜', '＋', '＝', '＿', '＾',
            '￥', '￣', '｀','≥',"≤","《","》"
        );
        $SBC = Array(// 半角
            '0', '1', '2', '3', '4',
            '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E',
            'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y',
            'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i',
            'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x',
            'y', 'z', '-', ' ', ':',
            '.', ',', '/', '%', '#',
            '!', '@', '&', '(', ')',
            '<', '>', '"', '\'', '?',
            '[', ']', '{', '}', '\\',
            '|', '+', '=', '_', '^',
            '$', '~', '`','>=',"<=","<=",">="
        );
        if ($args2 == 0) {
            return str_replace($SBC, $DBC, $str);  // 半角到全角
        } else if ($args2 == 1) {
            return str_replace($DBC, $SBC, $str);  // 全角到半角
        } else {
            return false;
        }
    }

    public static function get_nums_bystr($str) {
        if (empty($str)) {
            return array();
        }
        $temp = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.');
        $mumList = array();
        $result = '';

        for ($i = 0; $i < strlen($str); $i++) {
            if (in_array($str[$i], $temp)) {

                if (is_numeric($str[$i])) {
                    $result.=$str[$i];
                }
                if ($str[$i] == '.' && isset($str[$i - 1]) && is_numeric($str[$i - 1])) {
                    $result.=$str[$i];
                }

                if (($i + 1) == strlen($str)) {
                    $mumList[] = $result;
                    $result = '';
                }
            } else {
                $mumList[] = $result;
                $result = '';
            }
        }
        $mumList = array_values(array_filter($mumList));
        return $mumList;
    }

//http raw请求
    public static function curls($url, $data_string) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36'
        ));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

//自定义目录
    public static function customCheckpath($path) {
        $pathes = explode(DIRECTORY_SEPARATOR, $path);
        $dir = '';
        foreach ($pathes as $k => $v) {
            if ($v) {
                $dir .= $v . DIRECTORY_SEPARATOR;
                if (!is_dir($dir)) {
                    if (@mkdir($dir, 0777)) {
                        chmod($dir, 0777);
                    } else {
                        return false;
                    }
                }
            }
        }
        return $path;
    }

    public static function sql_error($errorCode, $errorMessage) {
        if ($errorCode == '42S22') {
            $errorMessage = explode("'", $errorMessage)[1];
            $errorMessage = str_replace('{field}', $errorMessage, trans('common.0x000007'));
            header('Content-Type: application/json', false, 200);
            echo json_encode(error_response('0x000007', '', [$errorMessage]));
            exit;
        }

        return false;
    }

    /**
     * [unique_arr 去除二维数组重复值]
     * @return [type] [返回值是二维数组]
     */
    public static function unique_arr($array2D, $stkeep = false, $ndformat = true) {

        // 判断是否保留一级数组键 (一级数组键可以为非数字)
        if ($stkeep)
            $stArr = array_keys($array2D); //返回数据的下标





































































// 判断是否保留二级数组键 (所有二级数组键必须相同)
        if ($ndformat)
            $ndArr = array_keys(end($array2D)); //返回二维数组的最后一个下标





































































//降维,也可以用implode,将一维数组转换为用逗号连接的字符串,结果是索引一维数组
        foreach ($array2D as &$v) {
            if (isset($v['pivot'])) {
                unset($v['pivot']);
            }
            $v = implode(",", $v);
            $temp[] = $v;
        }

        //去掉重复的字符串,也就是重复的一维数组
        $temp = array_unique($temp);

        //再将拆开的数组重新组装
        foreach ($temp as $k => $v) {
            if ($stkeep)
                $k = $stArr[$k];
            if ($ndformat) {
                $tempArr = explode(",", $v);
                foreach ($tempArr as $ndkey => $ndval)
                    $output[$k][$ndArr[$ndkey]] = $ndval;
            } else
                $output[$k] = explode(",", $v);
        }

        return $output;
    }

    /**
     * @返回成功响应信息
     * @param type $data 响应数据,data不传默认只返回状态
     * @return array 成功响应信息
     */
    public static function successResponse($data = false) {
        return static::handleResponse($data, 1, 'data');
    }

    /**
     * @返回警告响应信息
     * @param type $code 错误编码，为字符串或数组
     * @param type $langName 对应的语言包文件名
     * @param type $dynamic 动态错误信息，优先语言包使用 ；为字符串或数组(与错误编码数组元素对应写入)
     * @return array 警告响应信息
     */
    public static function warningResponse($code, $langName = '', $dynamic = '') {
        return static::handleResponse(static::handleErrorCode($code, $langName, $dynamic), 1);
    }

    /**
     * @返回错误响应信息
     * @param type $code 错误编码，为字符串或数组
     * @param type $langName 对应的语言包文件名
     * @param type $dynamic 动态错误信息，优先语言包使用 ；为字符串或数组(与错误编码数组元素对应写入)
     * @return array 错误响应信息
     */
    public static function errorResponse($code, $langName = '', $dynamic = '') {
        return static::handleResponse(static::handleErrorCode($code, $langName, $dynamic));
    }

    public static function hisErrorResponse($code, $langName, $apino, $apicode) {
        $message = trans($langName . '.' . $code);
        $result["api_no"] = $apino;
        $result["code"] = $apicode;
        $result["inner_code"] = $message;
        $result["message"] = $message;
        $result["description"] = "";
        $result["token"] = "";
        $result['runtime'] = round(microtime(true) - LARAVEL_START, 3);

        //记录api执行时间
        $appDebug = env('APP_DEBUG', false);
        $apiExecuteTime = env('API_EXECUTE_TIME', 1000);
        $runTime = $result['runtime'] * 1000;
        if ($appDebug && $runTime > $apiExecuteTime) {
            Blogger::getLogger('api_execute_time')->info(Request::path(), [$runTime . 'ms']);
        }
        return $result;
    }

    public static function hisSuccessResponse($data) {

        $result["api_no"] = "";
        $result["code"] = "";
        $result["inner_code"] = "";
        $result["message"] = " ";
        $result["description"] = "";
        $result["token"] = "";

        $result["data"] = isset($data["data"]) ? $data["data"] : [];


        $result['runtime'] = round(microtime(true) - LARAVEL_START, 3);

        //记录api执行时间
        $appDebug = env('APP_DEBUG', false);
        $apiExecuteTime = env('API_EXECUTE_TIME', 1000);
        $runTime = $result['runtime'] * 1000;
        if ($appDebug && $runTime > $apiExecuteTime) {
            Blogger::getLogger('api_execute_time')->info(Request::path(), [$runTime . 'ms']);
        }
        $extra = isset($data["extra"]) ? $data["extra"] : [];
        $result = array_merge($result, $extra);
        return $result;
    }

    public static function ListSuccessResponse($data) {


        $result["code"] = 1;
        $result["message"] = "success";
        $result["description"] = "";
        $result["token"] = "";
        $result['total'] = isset($data["total"]) ? $data["total"] : 0;
        $result["data"] = isset($data["data"]) ? $data["data"] : [];


        $result['runtime'] = round(microtime(true) - LARAVEL_START, 3);

        //记录api执行时间
        $appDebug = env('APP_DEBUG', false);
        $apiExecuteTime = env('API_EXECUTE_TIME', 1000);
        $runTime = $result['runtime'] * 1000;
        if ($appDebug && $runTime > $apiExecuteTime) {
            Blogger::getLogger('api_execute_time')->info(Request::path(), [$runTime . 'ms']);
        }
        return $result;
    }

    /**
     * @处理错误信息
     * @param type $code
     * @param type $langName
     * @param type $dynamic
     * @return array 错误信息
     */
    public static function handleErrorCode($code, $langName, $dynamic) {
        if (is_string($code)) {

            return [
                'code' => $code,
                'message' => trans($langName . '.' . $code)
            ];
        }

        $errors = [];
        foreach ($code as $k => $v) {
            if (is_array($langName)) {
                $langCode = $langName[$k] . '.' . $v;
            } else {
                $langCode = $langName . '.' . $v;
            }
            $errors[] = [
                'code' => $v,
                'message' => trans($langCode)
            ];
        }
        return $errors;
    }

    /**
     * @处理响应信息
     * @param type $messages
     * @param type $status
     * @param type $messageStatus
     * @return array 响应信息
     */
    public static function handleResponse($messages, $status = 0, $messageStatus = 'errors') {


        //正确返回结果
        if ($status == 1) {
            $result["api_no"] = "";
            $result["code"] = 1;
            $result["inner_code"] = "";
            $result["message"] = "success";
            $result["description"] = "";
            $result["token"] = "";
        } else {
            $result["api_no"] = "";
            $result["code"] = isset($messages["code"]) ? $messages["code"] : $messageStatus;
            $result["inner_code"] = isset($messages["message"]) ? $messages["message"] : $messageStatus;
            $result["message"] = isset($messages["message"]) ? $messages["message"] : $messageStatus;
            $result["description"] = "";
            $result["token"] = "";
            $result["data"] = [];
        }
        if ($messages !== false) {
            $result[$messageStatus] = $messages;
        }
        $result['runtime'] = round(microtime(true) - LARAVEL_START, 3);

        //记录api执行时间
        $appDebug = env('APP_DEBUG', false);
        $apiExecuteTime = env('API_EXECUTE_TIME', 1000);
        $runTime = $result['runtime'] * 1000;
        if ($appDebug && $runTime > $apiExecuteTime) {
            Blogger::getLogger('api_execute_time')->info(Request::path(), [$runTime . 'ms']);
        }

        return $result;
    }

    /**
     * 将一些特殊字符实体化
     *
     * @param string $val
     *
     * @return string
     */
    public static function convertValue($val) {
        if ("" == $val) {
            return "";
        }

        $val = str_replace("&#032;", " ", $val);

        $val = str_replace("&", "&amp;", $val);
        $val = str_replace("<!--", "&#60;&#33;--", $val);
        $val = str_replace("-->", "--&#62;", $val);
        $val = preg_replace("/<script/i", "&#60;script", $val);
        $val = str_replace(">", "&gt;", $val);
        $val = str_replace("<", "&lt;", $val);
        $val = str_replace("\"", "&quot;", $val);
        $val = preg_replace("/\n/", "<br />", $val); // Convert literal newlines
        $val = preg_replace("/\\\$/", "&#036;", $val);
        $val = preg_replace("/\r/", "", $val); // Remove literal carriage returns
        $val = str_replace("!", "&#33;", $val);
        $val = str_replace("'", "&#39;", $val); // IMPORTANT: It helps to increase sql query safety.

        if (get_magic_quotes_gpc()) {
            $val = stripslashes($val);
        }

        return $val;
    }

    /**
     * CURL获取信息 //--cookie.txt 需要测试
     *
     * @param string $url
     *
     * @param array $postFields
     *
     * @param bool $json
     *
     * @return type
     *
     */
    public static function getHttps($url, $postFields = "", $status = false) {

        $header = array(
            'Accept:application/json, text/javascript, */*',
            'Content-Type:application/x-www-form-urlencoded',
            'Referer:https://mp.weixin.qq.com/'
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_FAILONERROR, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //关闭直接输出
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //10秒
        if ($status) {
            curl_setopt($ch, CURLOPT_POST, 1); //使用post提交数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); //设置 post提交的数据
        }
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36'); //设置用户代理
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //设置头信息
        //curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
        $resultData = curl_exec($ch);
        curl_close($ch);

        return $resultData;
    }

    /*
     * 加密
     * @param string $txt 需要加密的字符串
     * @param string $key 加密key
     */

    public static function encrypt($txt, $key = "eoffice") {
        srand((double) microtime() * 1000000);
        $encrypt_key = md5(rand(0, 32000));
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
        }
        return base64_encode(static::passport_key($tmp, $key));
    }

    /*
     * 解密
     * @param string $txt 需要解密的字符串
     * @param string $key 解密key(需要于加密key一致，否则无法解密)
     */

    public static function decrypt($txt, $key = "eoffice") {
        $txt = static::passport_key(base64_decode($txt), $key);
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $md5 = $txt[$i];
            $tmp .= $txt[++$i] ^ $md5;
        }
        return $tmp;
    }

    /*
     * 加密、解密key解析
     * @param string $txt 需加、解密的字符串
     * @param string $encrypt_key 加、解密key
     */

    public static function passport_key($txt, $encrypt_key) {
        $encrypt_key = md5($encrypt_key);
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
        }
        return $tmp;
    }

    public static function getAge($birthday) {

        $age = strtotime($birthday);
        if ($age === false) {
            return false;
        }
        list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
        $now = strtotime("now");
        list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
        $age = $y2 - $y1;
        if ((int) ($m2 . $d2) < (int) ($m1 . $d1))
            $age -= 1;
        return $age;
    }
    
    
     public static function getGender($sex) {
        $sexSign = "";
        if ($sex == 0) {
            $sexSign = "男";
        } else if ($sex == 1) {
            $sexSign = "女";
        }
        return $sexSign;
    }
    
    public static function planVisitLevel($date){ 
        $time1 = strtotime($date);
        $time2 = time(); 
        $year1  = date("Y",$time1);   // 时间1的年份
        $month1 = date("m",$time1);   // 时间1的月份

        $year2  = date("Y",$time2);   // 时间2的年份
        $month2 = date("m",$time2);   // 时间2的月份
        
        return ($year2 * 12 + $month2) - ($year1 * 12 + $month1);
        
        
    }
    
    public static function isExistIncludeStr($haystack, $needle, $offset = 0){
        if (strpos($haystack, $needle) !== false) {
            //存在
            return TRUE;
        }

        return FALSE;
    }
    
    
    public static function getGenderNum($sex) {
        $sex = intval($sex);
        $gender = null;
        switch ($sex) {
            case 1:
                $gender = 0;
                break;
            case 0:
                $gender = 1;
                 break;
        }
        return $gender;
    }

    
    
    //年龄
    public static function getBday($birthday) {
        $age = strtotime($birthday);
        if ($age === false) {
            return null;
        }
        list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
        $now = strtotime("now");
        list($y2, $m2, $d2) = explode("-", date("Y-m-d", $now));
        $age = $y2 - $y1;
        if ((int) ($m2 . $d2) < (int) ($m1 . $d1))
            $age -= 1;
        return $age;
    }

    //计算病程
    public static function tranferDate($str) {
        $str = str_replace("年", "-", $str);
        $str = str_replace("月", "-", $str);
        $str = str_replace("日", "-", $str);

        return trim($str, "-");
    }

    public static function diffDate($date1, $date2, $day = true) {

        if (strtotime($date1) > strtotime($date2)) {
            $tmp = $date2;
            $date2 = $date1;
            $date1 = $tmp;
        }
        $arr1 = explode('-', trim($date1));
        $arr2 = explode('-', trim($date2));
        $Y1 = $arr1[0];
        $M1 = $arr1[1];
        $D1 = $arr1[2];

        $Y2 = $arr2[0];
        $M2 = $arr2[1];
        $D2 = $arr2[2];

        $Y = $Y2 - $Y1;
        $M = $M2 - $M1;
        $D = $D2 - $D1;
        if ($D < 0) {
            $D += (int) date('t', strtotime("-1 month $date2"));
            $M--;
        }
        if ($M < 0) {
            $M += 12;
            $Y--;
        }
        $ymd = "";
        if ($Y) {
            $ymd .= $Y . "年";
        }
        if ($M) {
            $ymd .= $M . "个月";
        }
        if ($D && $day) {
            $ymd .= $D . "天";
        }

        return $ymd;
    }
    
    public static function  imageUpdateSize($picname, $maxx = 100, $maxy = 100, $pre = "s_") {
        $info = getimageSize($picname); //获取图片的基本信息

        $w = $info[0]; //获取宽度
        $h = $info[1]; //获取高度
        //获取图片的类型并为此创建对应图片资源    
        switch ($info[2]) {
            case 1: //gif
                $im = @imagecreatefromgif($picname);
                break;
            case 2: //jpg
                $im = @imagecreatefromjpeg($picname);
                break;
            case 3: //png
                $im = @imagecreatefrompng($picname);
                break;
            case 6: //bmp
                $im = @imagecreatefrombmp($picname);
                break;
            default:
                die("图片类型错误！");
        }

        //计算缩放比例
        if (($maxx / $w) > ($maxy / $h)) {
            $b = $maxy / $h;
        } else {
            $b = $maxx / $w;
        }

        //计算出缩放后的尺寸
        $nw = floor($w * $b);
        $nh = floor($h * $b);

        //创建一个新的图像源(目标图像)
        $nim = imagecreatetruecolor($nw, $nh);

        //执行等比缩放
        imagecopyresampled($nim, $im, 0, 0, 0, 0, $nw, $nh, $w, $h);

        //输出图像（根据源图像的类型，输出为对应的类型）
        $picinfo = pathinfo($picname); //解析源图像的名字和路径信息
        $newpicname = $picinfo["dirname"] . "/"  .$pre. $picinfo["basename"];
        switch ($info[2]) {
            case 1:
                imagegif($nim, $newpicname);
                break;
            case 2:
                imagejpeg($nim, $newpicname);
                break;
            case 3:
                imagepng($nim, $newpicname);
                break;
        }
        //释放图片资源
        imagedestroy($im);
        imagedestroy($nim);
        //返回结果
        return $newpicname;
    }
    
            
    
}
